<?php

// +----------------------------------------------------------------------
// | Library for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2018 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://library.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github 仓库地址 ：https://github.com/zoujingli/ThinkLibrary
// +----------------------------------------------------------------------

namespace util;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * CURL数据请求管理器
 * Class Http
 * @package library\tools
 */
class Http
{
    /**
     * POST数据过滤处理
     * @param array $data 需要处理的数据
     * @param boolean $build 是否编译数据
     * @return array|string
     */
    private static function buildQueryData($data, $build = true)
    {
        if (!is_array($data)) return $data;
        foreach ($data as $key => $value){
            if (is_object($value) && $value instanceof \CURLFile) {
                $build = false;
            } elseif (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
                if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
                    list($build, $data[$key]) = [false, new \CURLFile($filename)];
                }
            }
        }
        return $build ? http_build_query($data) : $data;
    }
    
    public static function http_get($url,&$curlInfo)
    {
        $client = new Client();
        // 发送GET请求
        try {
            $response = $client->request('GET', $url, [
                'on_stats' => function ($stats) use(&$curlInfo) {
                    // 访问 cURL 请求的相关信息
                    // echo "Transfer time: " . $stats->getTransferTime() . " seconds\n";
                    // echo "Effective URL: " . $stats->getEffectiveUri() . "\n";

                    // 获取 cURL 获取的更多信息
                    $curlInfo = $stats->getHandlerStats();
                }
            ]);
            // echo "Response: " . $response->getBody();
            $getBody=$response->getBody()->__toString();
            $getBody=='{"error":"Document not found"}'?$curlInfo['download_content_length']=-1:'';
            return $getBody;
        } catch (RequestException $e) {
            // echo "Request failed: " . $e->getMessage();
        }
        return '';
    }
}